package cn.iocoder.yudao.module.engine.controller.app.asr;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.engine.controller.app.asr.vo.AppAudioToTextResVO;
import cn.iocoder.yudao.module.engine.constant.EngineErrorCodeConstants;
import cn.iocoder.yudao.module.infra.asr.AsrServiceFactory;
import cn.iocoder.yudao.module.engine.util.AudioConverterUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 APP - 语音识别")
@RestController
@RequestMapping("/lm/asr")
@Validated
@Slf4j
public class AppAsrController {
    @Resource
    private AsrServiceFactory asrServiceFactory;

    @PostMapping(value = "/audio-to-text")
    @Operation(summary = "创建消息")
    @PreAuthenticated
    public CommonResult<AppAudioToTextResVO> audioToText(@RequestParam(value = "audioFormat") String audioFormat,
                                                         @RequestPart(value = "audio") MultipartFile audio) {
        if (audio.isEmpty()) {
            log.warn("音频文件不能为空");
            throw exception(EngineErrorCodeConstants.ASR_ERROR, "音频文件不能为空");
        }

        final String text = doAudioToText(audioFormat, audio);

        final AppAudioToTextResVO res = new AppAudioToTextResVO(text);
        return success(res);
    }

    private String doAudioToText(String audioFormat, MultipartFile audio) {
        final String text;
        try {
            if ("webm".equals(audioFormat)) {
                final byte[] mp3ByteArray = AudioConverterUtils.convertWebmToMp3(audio.getInputStream());
                log.info("转换音频格式, mp3ByteArray.len = {}", mp3ByteArray.length);
                text = asrServiceFactory.getService().audioToText("mp3", mp3ByteArray);
            } else {
                text = asrServiceFactory.getService().audioToText(audioFormat, audio.getInputStream());
            }
        } catch (Exception e) {
            log.warn("读取音频文件异常", e);
            throw exception(EngineErrorCodeConstants.ASR_ERROR, "读取音频文件异常: " + e.getMessage());
        }
        return text;
    }

}